/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TelaFinTransferencia.java
 *
 * Created on 05/07/2011, 21:53:01
 */
package asfabdesk.apresentacao;

import asfabdesk.dominio.DepositoFinanceiro;
import asfabdesk.dominio.EntradaTransferencia;
import asfabdesk.dominio.HistoricoFinanceiro;
import asfabdesk.dominio.SaidaTransferencia;
import asfabdesk.presistencia.DAO;
import asfabdesk.util.Util;
import java.util.List;
import javax.swing.JOptionPane;

/**
 *
 * @author Marco Aurelio
 */
public class TelaFinTransferencia extends javax.swing.JInternalFrame {

    private DepositoFinanceiro depOrigem = new DepositoFinanceiro();
    private DepositoFinanceiro depDestino = new DepositoFinanceiro();
    private SaidaTransferencia saidaT = new SaidaTransferencia();
    private EntradaTransferencia entradaT = new EntradaTransferencia();
    private double valor = 0;

    /** Creates new form TelaFinTransferencia */
    public TelaFinTransferencia() {
        initComponents();
        configurarDepositoOrigem();
    }

    public void efetuarTranferencia() {
        if (verificaCampos()) {
            povoarVariaveis();
            povoarSaidaT();
            povoarEntradaT(saidaT);
            try {
                atualizarFundoModetarioDepositoDestino();
                atualizarFundoModetarioDepositoOrigem();
                salvarHistoricoSaidaT(saidaT);
                salvarHistoricoEntradaT(entradaT);
                JOptionPane.showMessageDialog(null, "Transferência realizada com Sucesso!","Sucesso",0);
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, "Ops, Ocorreu um problema durante a Transferência!","Ops",2);
            }
        }
    }

    public void povoarVariaveis() {
        DAO dao = new DAO();
        depOrigem = dao.localizar(DepositoFinanceiro.class, "depositoPorNome", comboOrigem.getSelectedItem().toString());
        depDestino = dao.localizar(DepositoFinanceiro.class, "depositoPorNome", comboDestino.getSelectedItem().toString());
        valor = new Util().getNumero(txtValor.getText());
    }

    public void povoarSaidaT() {
        saidaT.setDepositoDestino(depDestino);
        saidaT.setObservacao(txtObs.getText());
        saidaT.setSaldoAnteriorOrigem(depOrigem.getFundoMonetario());
        saidaT.setValorTransf(valor);
        saidaT.setSaldoPostOrigem(depOrigem.getFundoMonetario() - valor);
    }

    public void povoarEntradaT(SaidaTransferencia saida) {
        entradaT.setSaidaTransferencia(saida);
        entradaT.setDepositoOrigem(depOrigem);
        entradaT.setSaldoAnterior(depDestino.getFundoMonetario());
        entradaT.setSaldoPost(depDestino.getFundoMonetario() + valor);
    }

    public void atualizarFundoModetarioDepositoOrigem() {
        depOrigem.setFundoMonetario(depOrigem.getFundoMonetario() - valor);
        new DAO().salvar(depOrigem);
    }

    public void atualizarFundoModetarioDepositoDestino() {
        depDestino.setFundoMonetario(depDestino.getFundoMonetario() + valor);
        new DAO().salvar(depDestino);
    }

    public void configurarDepositoOrigem() {
        List depositos = (new DAO()).listar(DepositoFinanceiro.class, "depositoAptoTransf");
        for (int i = 0; i < depositos.size(); i++) {
            String descricao = ((DepositoFinanceiro) depositos.get(i)).getDescricao();
            comboOrigem.addItem(descricao);
        }
        comboOrigem.addItem("");
        comboOrigem.setSelectedItem("");
    }

    public void acaoComboOrigem() {
        String origem = comboOrigem.getSelectedItem().toString();
        if (origem.equals("")) {
            comboDestino.removeAllItems();
            comboDestino.addItem("");
            comboDestino.setSelectedItem("");
        } else {
            configurarDepositoDestino(origem);
        }
    }

    public void configurarDepositoDestino(String origem) {
        comboDestino.removeAllItems();
        List depositos = (new DAO()).listar(DepositoFinanceiro.class, "depositoAtivo");
        for (int i = 0; i < depositos.size(); i++) {
            String descricao = ((DepositoFinanceiro) depositos.get(i)).getDescricao();
            if (descricao.equals(origem)) {
                //não adiciona
            } else {
                comboDestino.addItem(descricao);
            }
        }
        comboDestino.addItem("");
        comboDestino.setSelectedItem("");
    }

    public void salvarHistoricoSaidaT(SaidaTransferencia transf) {
        HistoricoFinanceiro historico = new HistoricoFinanceiro();
        historico.setSaidaTransf(transf);
        historico.setTipo(4);
        historico.setMotivo(8);
        historico.setDepositoFinanceiro(depOrigem);
        new DAO().salvar(historico);
    }

    public void salvarHistoricoEntradaT(EntradaTransferencia transf) {
        HistoricoFinanceiro historico = new HistoricoFinanceiro();
        historico.setEntradaTransf(transf);
        historico.setTipo(3);
        historico.setMotivo(7);
        historico.setDepositoFinanceiro(depDestino);
        new DAO().salvar(historico);
    }

    public boolean verificaCampos() {
        boolean r = true;
        StringBuffer campos = new StringBuffer();
        String campo;

        if (comboOrigem.getSelectedItem().toString().equals("")) {
            campo = "(Depósito Origem) ";
            campos.append(campo);
            r = false;
        }

        if (comboDestino.getSelectedItem().toString().equals("")) {
            campo = "(Depósito Destino) ";
            campos.append(campo);
            r = false;
        }

        if (txtValor.getText().equals("") || txtValor.getText().equals("0,00") || txtValor.getText().equals("0")) {
            campo = "(Valor Zerado) ";
            campos.append(campo);
            r = false;
        }

        if (txtObs.getText().equals("")) {
            campo = "(Observação obrigatória) ";
            campos.append(campo);
            r = false;
        }

        if (r == false) {
            JOptionPane.showMessageDialog(null, "Ops, você não preencheu o(s) seguinte(s) campo(s) obrigatório(s): " + '\n' + campos, "Campos Obrigatórios.", 2);
        }
        return r;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        comboOrigem = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        comboDestino = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        txtValor = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtObs = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        btnConfirmar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(asfabdesk.apresentacao.AsfabDeskApp.class).getContext().getResourceMap(TelaFinTransferencia.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(resourceMap.getString("jPanel1.border.title"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        comboOrigem.setName("comboOrigem"); // NOI18N
        comboOrigem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboOrigemActionPerformed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        comboDestino.setName("comboDestino"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        txtValor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("###,###,##0.00"))));
        txtValor.setText(resourceMap.getString("txtValor.text")); // NOI18N
        txtValor.setName("txtValor"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        txtObs.setColumns(20);
        txtObs.setRows(5);
        txtObs.setName("txtObs"); // NOI18N
        jScrollPane1.setViewportView(txtObs);

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        btnConfirmar.setIcon(resourceMap.getIcon("btnConfirmar.icon")); // NOI18N
        btnConfirmar.setText(resourceMap.getString("btnConfirmar.text")); // NOI18N
        btnConfirmar.setName("btnConfirmar"); // NOI18N
        btnConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfirmarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(resourceMap.getIcon("btnCancelar.icon")); // NOI18N
        btnCancelar.setText(resourceMap.getString("btnCancelar.text")); // NOI18N
        btnCancelar.setName("btnCancelar"); // NOI18N
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(btnConfirmar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(comboOrigem, 0, 223, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtValor, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
                            .addComponent(comboDestino, 0, 221, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(comboOrigem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comboDestino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void comboOrigemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboOrigemActionPerformed
        acaoComboOrigem();
    }//GEN-LAST:event_comboOrigemActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmarActionPerformed
        efetuarTranferencia();
    }//GEN-LAST:event_btnConfirmarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JComboBox comboDestino;
    private javax.swing.JComboBox comboOrigem;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtObs;
    private javax.swing.JFormattedTextField txtValor;
    // End of variables declaration//GEN-END:variables
}
